<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    append-to-body
    title="查看信息"
    width="800px"
    top="30px"
  >
    <table class="table table-bordered table-vertical-middle">
      <colgroup>
        <col width="25%" />
        <col width="25%" />
        <col width="25%" />
        <col width="25%" />
      </colgroup>
      <tr>
        <td class="bg-light">抵质押物类型：</td>
        <td class="text-center" :class="tdClass">
          <span v-if="viewMode">{{ enumPledgeType[formData.guaranty_type] }}</span>
          <c-select
            v-else
            v-model="editData.guaranty_type"
            placeholder="类型"
            :options="enumPledgeType"
          ></c-select>
        </td>
        <td class="bg-light">抵质押物名称：</td>
        <td class="text-center" :class="tdClass">
          <span v-if="viewMode">{{ formData.guaranty_name }}</span>
          <el-input
            v-else
            v-model="editData.guaranty_name"
            autosize
            type="textarea"
            placeholder="名称"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="bg-light">抵押编号：</td>
        <td class="text-center" :class="tdClass">
          <span v-if="viewMode">{{ formData.guaranty_no }}</span>
          <el-input
            v-else
            v-model="editData.guaranty_no"
            autosize
            type="textarea"
            placeholder="编号"
          ></el-input>
        </td>
        <td class="bg-light">评估价值（元）：</td>
        <td class="text-center" :class="tdClass">
          <span v-if="viewMode">{{ formData.guaranty_value }}</span>
          <el-input
            v-else
            v-model="editData.guaranty_value"
            v-input-number="{ min: 0, fixed: 2 }"
            placeholder="估价（元）"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="bg-light">操作人：</td>
        <td class="text-center">
          <span v-if="viewMode">{{ formData.submit_person_name }}</span>
          <span v-else>{{ realName }}</span>
        </td>
        <td class="bg-light">操作时间：</td>
        <td class="text-center" :class="tdClass">
          <span v-if="viewMode">{{ dateFormat(formData.guaranty_date, 'yyyy年MM月dd日') }}</span>
          <el-date-picker
            v-else
            class="w-100"
            v-model="editData.guaranty_date"
            type="date"
            placeholder="操作时间"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
      </tr>
      <tr>
        <td class="bg-light">备注说明：</td>
        <td colspan="3" :class="tdClass">
          <span v-if="viewMode">{{ formData.remark }}</span>
          <el-input
            v-else
            v-model="editData.remark"
            :autosize="{ minRows: 4, maxRows: 100 }"
            type="textarea"
            placeholder="备注"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td colspan="4" class="bg-light">
          <div class="d-flex justify-content-between">
            <div>附件：</div>
            <div>
              <input type="file" ref="uploadInput" class="d-none" multiple />
              <el-button v-if="!viewMode" size="mini" @click="handleUpload">
                <i class="fa fa-fw fa-plus"></i>
                新增
              </el-button>
            </div>
          </div>
        </td>
      </tr>
      <tr>
        <td colspan="4">
          <div style="min-height: 100px">
            <div>
              <div v-for="(p, index) of attachArray" :key="index">
                <div class="d-flex">
                  <div :title="p.name" class="text-truncate file-name">{{ p.name }}</div>
                  <div>
                    <el-button type="text" class="p-0 my-0" @click="handleDownloadAready(p.url)">
                      下载
                    </el-button>
                    <el-button
                      type="text"
                      v-if="!viewMode"
                      @click="deleteImage(index)"
                      class="p-0 my-0"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-for="(p, index) of uploadFiles" :key="index">
              <div class="d-flex">
                <div :title="p.name" class="text-truncate file-name">{{ p.name }}</div>
                <div>
                  <el-button type="text" class="p-0 my-0" @click="handleDownloadUpload(p.file)">
                    下载
                  </el-button>
                  <el-button
                    type="text"
                    v-if="!viewMode"
                    @click="deleteUploadImage(index)"
                    class="p-0 my-0"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </td>
      </tr>
    </table>

    <div class="text-center" v-if="!viewMode">
      <el-button type="primary" class="btn-long" :loading="saveLoading" @click="handleSubmit">
        保存
      </el-button>
      <el-button class="btn-long" @click="beforeClose">取消</el-button>
    </div>

    <div class="text-center" v-if="isApprove">
      <el-button type="primary" class="btn-long" :loading="saveLoading" @click="handleSuccess">
        校验通过
      </el-button>
      <el-button type="danger" class="btn-long" :loading="saveLoading" @click="handleReject">
        校验未通过
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { enumPledgeType } from '@/credit/views/city/risk/pledge/enum'
import {
  add,
  arrayFromString,
  dateFormat,
  downloadByLink,
  stringFileName,
  arrayToString,
} from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { exportUrl } from '@/common/api/download'
import { addHistory } from '@/credit/views/city/archives/historyMixins'
export default {
  props: {
    visible: Boolean,
    viewMode: { type: Boolean, default: false },
    formData: {
      type: Object,
      default: () => ({}),
    },
    isApprove: {
      type: Boolean,
      default: false,
    },
    tableData: {
      type: Array,
      defualt: () => [],
    },
    queryId: String,
  },
  data() {
    return {
      dateFormat,
      enumPledgeType,
      editData: {},
      tableName: 'guaranty_register_detail',
      masterTableName: 'guaranty_register',
      uploadFiles: [],
      attachArray: [],
      saveLoading: false,
      deleteFiles: [],
      addFiles: [],
    }
  },
  computed: {
    ...mapGetters(['user', 'userId']),
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    realName() {
      return this.user.realName
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.editData = { ...this.formData }
        const data = arrayFromString(this.formData.attachment)
        this.attachArray = data.map(item => {
          return {
            url: item,
            name: item.replace(/.*\/(.*)$/, '$1'),
          }
        })
      },
      immediate: true,
      deep: true,
    },
    visible() {
      if (this.visible) {
        this.$nextTick(() => this.bindChangeListener())
      } else {
        this.$nextTick(() => this.offChangeListener())
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleSubmit() {
      const res = this.attachArray.map(it => it.url)
      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/pledge/${this.formData.guaranty_register_id}`,
          type: 0, // 用文件名
          progress: e => (it.percent = e.percent),
        })
      )
      this.saveLoading = true
      Promise.all(promises)
        .then(list => {
          this.addFiles = list
          list.forEach(it => res.push(it))
          this.saveData(arrayToString(res))
        })
        .catch(() => {
          this.saveLoading = false
        })
    },
    // 添加操作记录
    addHistoryRecord(archiveId) {
      if (!archiveId) {
        return
      }
      const getRecordItem = (key, label, newVal, oldVal, type) => ({
        update_record_field: key,
        update_record_field_name: label,
        update_record_id: archiveId,
        update_record_value_aft: newVal,
        update_record_value_bef: oldVal,
        update_type: type,
      })

      const masterData = {
        record_id: archiveId,
        submit_person: this.userId,
        submit_person_name: this.user.realName,
      }

      // 改变的数据
      const slaveData = []
      const config = [
        { key: 'guaranty_type', label: '抵质押物类型', getValue: v => enumPledgeType[v] },
        { key: 'guaranty_name', label: '抵质押物名称' },
        { key: 'guaranty_no', label: '抵押编号' },
        { key: 'guaranty_value', label: '评估价值（元）' },
        { key: 'submit_person_name', label: '操作人' },
        {
          key: 'guaranty_date',
          label: '抵押登记时间',
          getValue: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
        },
        { key: 'remark', label: '备注说明' },
      ]
      for (const cfg of config) {
        const { key, label, getValue } = cfg
        const oldVal = getValue ? getValue(this.formData[key]) : this.formData[key]
        const newVal = getValue ? getValue(this.editData[key]) : this.editData[key]
        if (newVal !== oldVal) {
          slaveData.push(getRecordItem(key, label, newVal, oldVal, 1))
        }
      }
      // 附件新增
      for (const fileUrl of this.addFiles) {
        slaveData.push(getRecordItem('attachment', '附件', fileUrl, '', 2))
      }
      // 附件删除
      for (const fileUrl of this.deleteFiles) {
        slaveData.push(getRecordItem('attachment', '附件', fileUrl, '', 3))
      }
      return addHistory(masterData, slaveData)
    },
    handleSuccess() {
      this.saveLoading = true
      const data = {
        item_guaranty_status: 2,
      }
      const master = {
        register_status: 2,
      }
      this.updateData(data, master)
        .then(() => {
          this.$emit('success', true)
          this.beforeClose()
          this.$message.success('检验通过！')
        })
        .catch(() => {
          this.$message.error('操作失败！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleReject() {
      this.saveLoading = true
      const data = {
        item_guaranty_status: 3,
      }
      const master = {
        register_status: 2,
      }
      this.updateData(data, master)
        .then(() => {
          this.$emit('success', true)
          this.beforeClose()
          this.$message.success('操作成功！')
        })
        .catch(() => {
          this.$message.error('操作失败！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    getDetailData(data) {
      return this.tableData.map(item => {
        if (item.id === this.formData.id) {
          return {
            id: item.id,
            guaranty_register_id: this.formData.guaranty_register_id,
            ...data,
          }
        } else {
          return {
            id: item.id,
            guaranty_register_id: this.formData.guaranty_register_id,
          }
        }
      })
    },
    getValueTotal() {
      let sum = 0
      this.tableData.forEach(item => {
        if (item.id === this.formData.id) {
          sum = add(sum, this.editData.guaranty_value)
        } else {
          sum = add(sum, item.guaranty_value)
        }
      })
      return sum
    },
    updateData(data, master = {}) {
      if (!this.formData.id) {
        return Promise.reject(new Error(''))
      }
      const masterData = {
        customer_related_id: this.queryId,
        guaranty_register_id: this.formData.guaranty_register_id,
        guaranty_value_total: this.getValueTotal(),
        ...master,
      }
      const dataArray = this.getDetailData(data)
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.masterTableName,
        slaveTableInfo: JSON.stringify(dataArray),
        slaveTableName: this.tableName,
      }
      return this.$api.relatedUpdate(this.$serviceName, formData)
    },
    saveData(url) {
      if (!this.formData.id) {
        return
      }
      const data = {
        attachment: url,
        guaranty_date: this.editData.guaranty_date,
        guaranty_name: this.editData.guaranty_name,
        guaranty_no: this.editData.guaranty_no,
        guaranty_type: this.editData.guaranty_type,
        guaranty_value: this.editData.guaranty_value,
        remark: this.editData.remark,
        submit_person_name: this.realName,
      }
      this.updateData(data)
        .then(() => {
          this.addHistoryRecord(this.formData.guaranty_register_id)
          this.$emit('success', true)
          this.$message.success('登记成功！')
        })
        .catch(() => {
          this.$message.error('登记失败')
        })
        .finally(() => {
          if (this.deleteFiles.length) {
            deleteOss(this.deleteFiles)
          }
          this.saveLoading = false
          this.beforeClose()
        })
    },
    deleteImage(index) {
      this.deleteFiles.push(this.attachArray[index].url)
      this.attachArray.splice(index, 1)
    },
    deleteUploadImage(index) {
      this.uploadFiles.splice(index, 1)
    },
    handleDownloadAready(url) {
      exportUrl({
        url,
        filename: stringFileName(url),
      })
    },
    // 下载
    handleDownloadUpload(file) {
      const { name, type } = file
      const url = window.URL.createObjectURL(new Blob([file]), { type })
      downloadByLink({ url, filename: name })
      window.URL.revokeObjectURL(url)
    },

    handleUpload() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },

    changeListener(e) {
      const { files = [] } = e.target
      // 把文件存入数组中
      const selectedFiles = []
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        selectedFiles.push({
          file,
          name: file.name,
          percent: 0,
        })
      }

      // 检查是否有相同名字的文件(直接覆盖)
      for (let i = 0; i < this.uploadFiles.length; i++) {
        const file = this.uploadFiles[i]
        const sameIndex = selectedFiles.findIndex(it => it.name === file.name)
        if (sameIndex > -1) {
          this.uploadFiles[i] = selectedFiles[sameIndex]
          selectedFiles.splice(sameIndex, 1)
        }
      }

      this.uploadFiles.push(...selectedFiles)
    },

    bindChangeListener() {
      const { uploadInput } = this.$refs
      uploadInput.addEventListener('change', this.changeListener.bind(this))
    },

    offChangeListener() {
      const { uploadInput } = this.$refs
      if (!uploadInput) return
      uploadInput.removeEventListener('change', this.changeListener.bind(this))
    },

    beforeClose() {
      this.deleteFiles = []
      this.uploadFiles = []
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
.file-name {
  width: 160px;
}
</style>
